﻿using CommonHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace DAQ_Desktop
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {

        [System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "CreateMutex")]
        public static extern IntPtr CreateMutex(int lpSecurityAttributes, bool bInitialOwner, string lpName);

        [System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "GetLastError")]
        public static extern int GetLastError();
        private const int ERROR_ALREADY_EXISTS = 183;
        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                //FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
                //var li = new SzlKaisen().SzlDecrypto(out string msg);
                //if (!li)
                //{
                //    MessageBox.Show(msg);
                //    Environment.Exit(0);
                //    Application.Current.Shutdown();
                //    return;
                //}
                string appTitle = "DAQ_DeskTop";
                IntPtr hMutex = CreateMutex(0, true, appTitle);
                if (GetLastError() == ERROR_ALREADY_EXISTS)
                {
                    MessageBox.Show("已有一个客户端正在运行,请先结束原来客户端!");
                    Environment.Exit(0);
                    Application.Current.Shutdown();
                    return;
                }
                //初始化
                if (DataCenter.Instance.Init())
                {
                    ////设置应用程序启动时自动打开的一个UI的一个URI,跳到MainWindow界面
                    //base.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
                }
            }
            catch (Exception ex)
            {
                LogHelper.logSysErr.Error("程序启动异常---"+ex);
                Environment.Exit(0);
                Application.Current.Shutdown();
                return;
            }



            base.OnStartup(e);
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            LogHelper.logSysErr.Error("TaskException" + e.ToString());
            e.SetObserved();
        }
        private void App_DispatcherUnhandleException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            LogHelper.logSysErr.Error("DispatcherException" + e.ToString());
            e.Handled = true;
        }
    }
}
